<?php

namespace App\Http\Controllers\Api\Miniprogram;

use App\Http\Controllers\Controller;
use App\Models\User\FamilyUser;
use Illuminate\Support\Facades\Auth;

class FamilyController extends Controller
{
    public function getUsers()
    {
        $user = Auth::user();
        $cnt = $user->familyUsers()->count();
        if ($cnt == 0) {
            $user->familyUsers()->firstOrCreate([
                'identity' => 1,
            ], [
                'name' => $user->name,
                'sex' => $user->sex,
                'phone' => $user->phone,
            ]);
        }
        return $this->successJson($user->familyUsers);
    }

    public function getUser()
    {
        $user = Auth::user();
        $id = request('id');
        $familyUser = $user->familyUsers()->where('id', $id)->first();
        return $this->successJson($familyUser);
    }

    public function saveUser()
    {
        $user = Auth::user();
        $id = request('id');
        $name = request('name');
        $sex = request('sex');
        $age = request('age');
        $identity = request('identity');
        $phone = request('phone');
        $idcard = request('idcard');
        if ($id) {
            $familyUser = $user->familyUsers()->where('id', $id)->first();
        } else {
            $familyUser = new FamilyUser();
            $familyUser->user_id = $user->id;
        }
        $familyUser->name = $name;
        if ($sex) {
            $familyUser->sex = $sex;
        }
        if ($age) {
            $familyUser->age = $age;
        }
        if ($identity) {
            $familyUser->identity = $identity;
        }
        if ($phone) {
            $familyUser->phone = $phone;
        }
        if ($idcard) {
            $familyUser->idcard = $idcard;
        }
        $familyUser->save();
        return $this->successJson();
    }
}
